﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using EZSockets;
using Common;
using System.IO;

namespace SimCNC
{       
    /******命名约定**************
     * Pascal大写小： 程序中类型名称和类中对外可见的成员，标识符中每个单词的首字母大写。包括类，方法，命名空间，属性和公共字段
     * Camel大小写：用于局部变量的名称和方法声明的形参名称，标识符中每个单词的首字母大小，第一个除外
     * _+Camel：用于私有和受保护的字段。
     ***************************/

    public partial class MitMain : Form
    {
        EZSockets.MitCom mitCom = new MitCom();

        System.Timers.Timer timer1 = new System.Timers.Timer(); //定义一个定时器用来刷新坐标，程序，报警等

        double pdspeed;//指令进给速度

        public MitMain()
        {
            InitializeComponent();

            //订阅报警事件
            mitCom.AlarmData += new Common.MyDelegate<string, string>(M_Server_keepAlarmInfo);
        }
        
        /// <summary>
        /// 解决大量窗体控件闪烁
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }

        #region 控件重绘
        private void ComGB_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.Clear(ComGB.BackColor);
            e.Graphics.DrawString(ComGB.Text, ComGB.Font, Brushes.Black, 10, 1);
            e.Graphics.DrawLine(Pens.Black, 1, 7, 8, 7);
            e.Graphics.DrawLine(Pens.Black, e.Graphics.MeasureString(ComGB.Text, ComGB.Font).Width + 8, 7, ComGB.Width - 2, 7);
            e.Graphics.DrawLine(Pens.Black, 1, 7, 1, ComGB.Height - 2);
            e.Graphics.DrawLine(Pens.Black, 1, ComGB.Height - 2, ComGB.Width - 2, ComGB.Height - 2);
            e.Graphics.DrawLine(Pens.Black, ComGB.Width - 2, 7, ComGB.Width - 2, ComGB.Height - 2);
        }

        private void AlarmGB_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.Clear(AlarmGB.BackColor);
            e.Graphics.DrawString(AlarmGB.Text, AlarmGB.Font, Brushes.Black, 10, 1);
            e.Graphics.DrawLine(Pens.Black, 1, 7, 8, 7);
            e.Graphics.DrawLine(Pens.Black, e.Graphics.MeasureString(AlarmGB.Text, AlarmGB.Font).Width + 8, 7, AlarmGB.Width - 2, 7);
            e.Graphics.DrawLine(Pens.Black, 1, 7, 1, AlarmGB.Height - 2);
            e.Graphics.DrawLine(Pens.Black, 1, AlarmGB.Height - 2, AlarmGB.Width - 2, AlarmGB.Height - 2);
            e.Graphics.DrawLine(Pens.Black, AlarmGB.Width - 2, 7, AlarmGB.Width - 2, AlarmGB.Height - 2);
        }


        private void groupBox7_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.Clear(groupBox7.BackColor);
            e.Graphics.DrawString(groupBox7.Text, groupBox7.Font, Brushes.Black, 10, 1);
            e.Graphics.DrawLine(Pens.Black, 1, 7, 8, 7);
            e.Graphics.DrawLine(Pens.Black, e.Graphics.MeasureString(groupBox7.Text, AlarmGB.Font).Width + 8, 7, groupBox7.Width - 2, 7);
            e.Graphics.DrawLine(Pens.Black, 1, 7, 1, groupBox7.Height - 2);
            e.Graphics.DrawLine(Pens.Black, 1, groupBox7.Height - 2, groupBox7.Width - 2, groupBox7.Height - 2);
            e.Graphics.DrawLine(Pens.Black, groupBox7.Width - 2, 7, groupBox7.Width - 2, groupBox7.Height - 2);
        }

        private void groupBox8_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.Clear(groupBox8.BackColor);
            e.Graphics.DrawString(groupBox8.Text, groupBox8.Font, Brushes.Black, 10, 1);
            e.Graphics.DrawLine(Pens.Black, 1, 7, 8, 7);
            e.Graphics.DrawLine(Pens.Black, e.Graphics.MeasureString(groupBox8.Text, AlarmGB.Font).Width + 8, 7, groupBox8.Width - 2, 7);
            e.Graphics.DrawLine(Pens.Black, 1, 7, 1, groupBox8.Height - 2);
            e.Graphics.DrawLine(Pens.Black, 1, groupBox8.Height - 2, groupBox8.Width - 2, groupBox8.Height - 2);
            e.Graphics.DrawLine(Pens.Black, groupBox8.Width - 2, 7, groupBox8.Width - 2, groupBox8.Height - 2);

        }

        private void groupBox2_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.Clear(groupBox2.BackColor);
            e.Graphics.DrawString(groupBox2.Text, groupBox2.Font, Brushes.Black, 10, 1);
            e.Graphics.DrawLine(Pens.Black, 1, 7, 8, 7);
            e.Graphics.DrawLine(Pens.Black, e.Graphics.MeasureString(groupBox2.Text, AlarmGB.Font).Width + 8, 7, groupBox2.Width - 2, 7);
            e.Graphics.DrawLine(Pens.Black, 1, 7, 1, groupBox2.Height - 2);
            e.Graphics.DrawLine(Pens.Black, 1, groupBox2.Height - 2, groupBox2.Width - 2, groupBox2.Height - 2);
            e.Graphics.DrawLine(Pens.Black, groupBox2.Width - 2, 7, groupBox2.Width - 2, groupBox2.Height - 2);
        }

        private void NCStatusGB_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.Clear(NCStatusGB.BackColor);
            e.Graphics.DrawString(NCStatusGB.Text, NCStatusGB.Font, Brushes.Black, 10, 1);
            e.Graphics.DrawLine(Pens.Black, 1, 7, 8, 7);
            e.Graphics.DrawLine(Pens.Black, e.Graphics.MeasureString(NCStatusGB.Text, ComGB.Font).Width + 8, 7, NCStatusGB.Width - 2, 7);
            e.Graphics.DrawLine(Pens.Black, 1, 7, 1, NCStatusGB.Height - 2);
            e.Graphics.DrawLine(Pens.Black, 1, NCStatusGB.Height - 2, NCStatusGB.Width - 2, NCStatusGB.Height - 2);
            e.Graphics.DrawLine(Pens.Black, NCStatusGB.Width - 2, 7, NCStatusGB.Width - 2, NCStatusGB.Height - 2);

        }

        private void PosGB_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.Clear(PosGB.BackColor);
            e.Graphics.DrawString(PosGB.Text, PosGB.Font, Brushes.Black, 10, 1);
            e.Graphics.DrawLine(Pens.Black, 1, 7, 8, 7);
            e.Graphics.DrawLine(Pens.Black, e.Graphics.MeasureString(PosGB.Text, ComGB.Font).Width + 8, 7, PosGB.Width - 2, 7);
            e.Graphics.DrawLine(Pens.Black, 1, 7, 1, PosGB.Height - 2);
            e.Graphics.DrawLine(Pens.Black, 1, PosGB.Height - 2, PosGB.Width - 2, PosGB.Height - 2);
            e.Graphics.DrawLine(Pens.Black, PosGB.Width - 2, 7, PosGB.Width - 2, PosGB.Height - 2);

        }

        private void AxisInfoTB_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.Clear(AxisInfoTB.BackColor);
            e.Graphics.DrawString(AxisInfoTB.Text, AxisInfoTB.Font, Brushes.Black, 10, 1);
            e.Graphics.DrawLine(Pens.Black, 1, 7, 8, 7);
            e.Graphics.DrawLine(Pens.Black, e.Graphics.MeasureString(AxisInfoTB.Text, AxisInfoTB.Font).Width + 8, 7, AxisInfoTB.Width - 2, 7);
            e.Graphics.DrawLine(Pens.Black, 1, 7, 1, AxisInfoTB.Height - 2);
            e.Graphics.DrawLine(Pens.Black, 1, AxisInfoTB.Height - 2, AxisInfoTB.Width - 2, AxisInfoTB.Height - 2);
            e.Graphics.DrawLine(Pens.Black, AxisInfoTB.Width - 2, 7, AxisInfoTB.Width - 2, AxisInfoTB.Height - 2);


        }
        #endregion

        /// <summary>
       ///  加载窗体
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="e"></param>
        private void MitMain_Load(object sender, EventArgs e)
        {
         
        }

        /// <summary>
        /// 定时器事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            GetRunStatus();
            GetAxisPosition();
            GetSpindleInfo();
            GetCount();
            GetNCAlarm();
            GetServoInfo();
            GetProgramItem();
          
  
        }

        /// <summary>
        /// 关闭窗体前退出系统，终止进程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SimMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            System.Environment.Exit(0);
        }

        /// <summary>
        /// 通讯事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Connect_Click(object sender, EventArgs e)
        {
            string version = "";
            int  pvValue;
            if (Connect.Text == "连接")
            {

                mitCom.GetSimConnect(NcTypeCmb.Text, NCCardNo.Text, TimeOut.Text, NodeName.Text);
                mitCom.GetSimVersion(1, 0, out version);
                mitCom.GetPLCPar(1008, out pvValue);
                this.NCCardVer.Text = version;
                //订阅定时器事件
                timer1.Interval = 1000;
                timer1.Elapsed += Timer1_Elapsed;
                timer1.Enabled = true;
                Connect.Text = "断开";
            }
            else
                if (Connect.Text == "断开")
                {
                    timer1.Enabled = false;
                    version = "";
                    mitCom.GetSimConnect(NcTypeCmb.Text, NCCardNo.Text, TimeOut.Text, NodeName.Text);
                    Connect.Text = "连接";
                    RunStatusTB.Text = "通讯已断开";
                }

        }

        /// <summary>
        /// 获取轴坐标
        /// </summary>
        void GetAxisPosition()
        {
            Communicationcs<string, string> maPos;
            mitCom.GetAxisPosition(3, out maPos);
            this.BeginInvoke((MethodInvoker)delegate()
            {
                if (maPos.simMaPos.Count == 3 && maPos.simCurPos.Count == 3 && maPos.simWorkPos.Count == 3 && maPos.simDisPos.Count == 3)
                {

                    meXTB.Text = maPos.simMaPos[0];
                    meYTB.Text = maPos.simMaPos[1];
                    meZTB.Text = maPos.simMaPos[2];
                    relXTB.Text = maPos.simCurPos[0];
                    relYTB.Text = maPos.simCurPos[1];
                    relZTB.Text = maPos.simCurPos[2];
                    abXTB.Text = maPos.simWorkPos[0];
                    abYTB.Text = maPos.simWorkPos[1];
                    abZTB.Text = maPos.simWorkPos[2];
                    disXTB.Text = maPos.simDisPos[0];
                    disYTB.Text = maPos.simDisPos[2];
                    disZTB.Text = maPos.simDisPos[2];

                }
            });

        }

        /// <summary>
        /// 获取运行状态
        /// </summary>
        void GetRunStatus()
        {
            List<string> status = new List<string>();
            int plstatus;
            for (int i = 0; i < 4; i++)
            {
                mitCom.GetRunStatus(i, out plstatus);
                switch (i)
                {
                    case 0:
                        if (plstatus == 0)
                        {
                            status.Add( "刀具未测量");
                        }
                        else
                        {
                            status.Add( "刀具已测量");
                        }
                        break;
                    case 1:
                        if (plstatus == 0)
                        {
                            status.Add("未自动运行");
                        }
                        else
                        {
                            status.Add("自动运行");
                        }
                        break;
                    case 2:
                        if (plstatus == 0)
                        {
                            status.Add("未开始自动运行");
                        }
                        else
                        {
                            status.Add("开始自动运行");
                        }
                        break;
                    case 3:
                        if (plstatus == 0)
                        {
                            status.Add("自动运行未暂停");
                        }
                        else
                        {
                           status.Add("自动运行暂停");
                        }
                        break;

                }
                
            }
            this.BeginInvoke((MethodInvoker)delegate()
            {
                RunStatusTB.Text = status[0] + "/" + status[1] + "/" + status[2] + "/" + status[3];
            });

        }

        /// <summary>
        /// 主轴信息
        /// </summary>
        void GetSpindleInfo()
        {
            int pdata;
            string loadstr;
            double pdspeedFM, pdspeedFS, pdspeedFE;
            List<string> info = new List<string>();
            mitCom.GetSpindleInfo(2, 1, out pdata, out loadstr);//转速
            info.Add(pdata.ToString());
            mitCom.GetSpindleInfo(3, 1, out pdata, out loadstr);//负载
            info.Add(pdata.ToString());
            mitCom.GetSpindleInfo(4, 1, out pdata, out loadstr);//LED
            info.Add(pdata.ToString());
            mitCom.GetSpindleInfo(5, 1, out pdata, out loadstr);//报警
            info.Add(pdata.ToString());
            mitCom.GetFeedSpeed(0, out pdspeed, "GetFeedSpeedFA"); //获取指令进给速度
            mitCom.GetFeedSpeed(1, out pdspeedFM, "GetFeedSpeedFM");//手动有效进给速度（FM）
            mitCom.GetFeedSpeed(2, out pdspeedFS, "GetFeedSpeedFS");//同步进给速度（FS）;
            mitCom.GetFeedSpeed(3, out pdspeedFE, "GetFeedSpeedFE");//攻丝（FE）;
            this.BeginInvoke((MethodInvoker)delegate()
            {
                txFA.Text = pdspeed.ToString();
                txFM.Text = pdspeedFM.ToString();
                txFS.Text = pdspeedFS.ToString();
                txFE.Text = pdspeedFE.ToString();
                txSpindleLoad.Text = info[0];
                txSpindleSpeed.Text = info[1];
                txSpindleAlarm.Text = info[3];
                if (pdspeed != 0)
                {
                    txDiff.Text = (Convert.ToInt32(info[1]) / pdspeed).ToString();
                }
                else
                {
                    txDiff.Text = "";
                }
                
            });
        }

        /// <summary>
        /// 获取伺服轴信息
        /// </summary>
        void GetServoInfo()
        {
            int plData;
            string loadStr;
            string alarmString=null;
            List<string> servoSpeedInfo = new List<string>();
            List<string> servoCurrentInfo = new List<string>();
            for (int i = 1; i <= 3; i++)
            {
                switch (i)
                {
                    case 1:
                        alarmString="Monitor_GetServoMonitorSpeed";
                        break ;
                    case 2: alarmString = "Monitor_GetServoMonitorCurrent";
                        break;
                        
                }
                mitCom.GetServoInfo(i, 2, out plData, out loadStr, alarmString);
                servoSpeedInfo.Add(plData.ToString());
                mitCom.GetServoInfo(i, 3, out plData, out loadStr, alarmString);
                servoCurrentInfo.Add(plData.ToString());
            }
            this.BeginInvoke((MethodInvoker)delegate()
            {
                txXSpeed.Text = servoSpeedInfo[0];
                txYSpeed.Text = servoSpeedInfo[1];
                txZSpeed.Text = servoSpeedInfo[2];
                txXCurrent.Text = servoCurrentInfo[0];
                txYCurrent.Text = servoCurrentInfo[1];
                txZCurrent.Text = servoCurrentInfo[2];
                //伺服进给倍率
                if (pdspeed != 0)
                {
                    txXDiff.Text = (Convert.ToInt32(servoSpeedInfo[0]) / pdspeed).ToString();
                    txYDiff.Text = (Convert.ToInt32(servoSpeedInfo[1]) / pdspeed).ToString();
                    txZDiff.Text = (Convert.ToInt32(servoSpeedInfo[2]) / pdspeed).ToString();
                }
                else
                {
                    txXDiff.Text = "";
                    txYDiff.Text = "";
                    txZDiff.Text = "";
                }
            });


        }

        /// <summary>
        /// 统计件数
        /// </summary>
        void GetCount()
        {
            string pvValue;
            mitCom.GetParaValue(30, 8002, 1, 1, out pvValue);
            this.BeginInvoke((MethodInvoker)delegate()
           {
               CountTB.Text = pvValue;
           });
        }

        /// <summary>
        /// 获取NC系统报警
        /// </summary>
        void GetNCAlarm()
        {
            string[] alarmMsg;
            mitCom.GetAlarm(out alarmMsg);
            this.BeginInvoke((MethodInvoker)delegate()
            {
                Alarm.Text = alarmMsg[0];
            });

        }

        /// <summary>
        /// 累计加工时间
        /// </summary>
        void GetTime()
        {
            int plTime;
            mitCom.GetRunTime(out plTime);
        }

        /// <summary>
        /// 获取程序内容
        /// </summary>
        void GetProgramItem()
        {
            int sequenceNo;
            string  programNumber;
            string program;
            mitCom.GetSequenceNo( out sequenceNo);
            mitCom.GetProgramNumber(out programNumber);
            mitCom.GetProgram(out program);
            this.BeginInvoke((MethodInvoker)delegate()
            {
                PrgNo.Text = programNumber;
                SequenceNo.Text = sequenceNo.ToString ();
                CurrentPrg.Items.Clear();
                string[] lStr = program.Split('\n');
                for (int i = 0; i < lStr.Length; i++)
                {
                    CurrentPrg.Items.Add(lStr[i]);
                }
            });

        }


        /// <summary>
        /// 系统报警事件
        /// </summary>
        /// <param name="message"></param>
        private string M_Server_keepAlarmInfo(string message)
        {
            this.Invoke((MethodInvoker)delegate()
            {
                EZError.AppendText(message + "\r\n");

            });
            return "";
        }

        /// <summary>
        /// 刀补信息界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
    
        private void button3_Click_1(object sender, EventArgs e)
        {
            this.panel1.Controls.Remove(NCStatusGB);
            ToolOffset toolOffset = new ToolOffset(mitCom);
            toolOffset.TopLevel = false;//这就是使你窗体变控件的一步
            toolOffset.Dock = System.Windows.Forms.DockStyle.Fill;
            toolOffset.FormBorderStyle = FormBorderStyle.None;
            toolOffset.Parent = this.panel1;
            this.panel1.Controls.Add(toolOffset);
            toolOffset.Show();         
        }

        /// <summary>
        /// NC状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            this.panel1.Controls.Clear();
            this.panel1.Controls.Add(button3);
            this.panel1.Controls.Add(button4);
            this.panel1.Controls.Add(NCStatusGB);
        }

        /// <summary>
        /// 读取NC程序到本地
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpLoadBtn_Click(object sender, EventArgs e)
        {
            string data;
            mitCom.ReadNcFile(10, out data,FileNameTB.Text );
            string fileName = "D:\\NCFile\\T1.NC";
            mitCom.UpdateNCPrgToCNC(fileName);
            if (data != null)
            {
                SaveText(data);
            }
        }

        


        /// <summary>
        /// 下载NC程序到设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DownLoadBtn_Click(object sender, EventArgs e)
        {
            //每次读取的字节数  
             OpenFileDialog openFileDialog = new OpenFileDialog();
             if (openFileDialog.ShowDialog() == DialogResult.OK)
             {
                 int iBufferSize =2048;
                 byte[] buffer = new byte[iBufferSize];
                 FileStream fs = null;
                 try
                 {
                     fs = new FileStream(openFileDialog.FileName, FileMode.Open);
                     //文件流的长度  
                     long lFileSize = fs.Length;
                     //文件需要读取次数  
                     int iTotalCount = (int)Math.Ceiling((double)(lFileSize / iBufferSize));
                     //当前读取次数  
                     int iTempCount = 0;

                     //while (iTempCount < iTotalCount)
                     //{
                         //每次从最后读到的位置读取下一个[iBufferSize]的字节数  
                         fs.Read(buffer, 0, iBufferSize);
                         //将字节转换成字符  
                         string strRead = Encoding.Default.GetString(buffer);
                         //此处加入你的处理逻辑  

                         mitCom.WriteNcFile(FileNameTB.Text, strRead);
                       
                         Console.Write(strRead);
                    // }
                 }
                 catch (Exception ex)
                 {
                     //异常处理  
                 }
                 finally
                 {
                     if (fs != null)
                     {
                         fs.Dispose();
                     }
                 }
             }
        }

        /// <summary>
        /// 打开加工程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpenFileBtn_Click(object sender, EventArgs e)
        {

        }

        #region 将文件保存到本地

        /// <summary>
        /// 写入文本文件
        /// </summary>
        /// <param name="value"></param>
        public void SaveText(string value)
        {
            change();
            string path = Application.StartupPath + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\TextMessage.txt";
            FileStream f = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
            StreamWriter sw = new StreamWriter(f);
            sw.WriteLine(value);
            sw.Flush();
            sw.Close();
            f.Close();
        }

        /// <summary>
        /// 检查是否存在文件夹
        /// </summary>
        public void change()
        {
            string path = Application.StartupPath + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\TextMessage.txt";
            if (!Directory.Exists(Application.StartupPath + "\\" + DateTime.Now.ToString("yyyy-MM-dd")))
            {
                Directory.CreateDirectory(Application.StartupPath + "\\" + DateTime.Now.ToString("yyyy-MM-dd"));
            }
            if (!File.Exists(path))
            {
                FileStream fs = File.Create(@"" + DateTime.Now.ToString("yyyy-MM-dd") + "\\TextMessage.txt");
                fs.Close();
            }
        }














        #endregion

        private void btnset_Click(object sender, EventArgs e)
        {

            mitCom.setPrograme();


        }
    }


}
